package com.zx.config;/**
 * Author:JasonZ
 * Data:2023/4/20
 */

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @program: ecommerce-parent
 * @description: 异步任务入库监视器
 * @author: JasonZ
 * @create: 2023-04-20 16:50
 **/
@Component
@Aspect //定义为切面
@Slf4j
public class AsyncTaskMonitor {

    @Resource
    private AsyncTaskManager taskManager;

    /*(..)表示有无参数*/
    @Around("execution(public * com.zx.service.Impl.AsyncGoodsServiceImpl.*(..))")
    public Object taskHandle(ProceedingJoinPoint joinPoint) {
        //joinPoint可以获得连接点当中的参数,方法名等等
        String taskId = joinPoint.getArgs()[1].toString();
        log.info("AsyncTaskMonitor is monitoring async task [{}]", taskId);
        AsyncTask task = taskManager.getTask(taskId);
        Object value = null;
        AsyncTaskStatus status = null;
        task.setId(taskId);
        try {
            value = joinPoint.proceed();// 让被代理的方法执行
            status = AsyncTaskStatus.SUCCESS;
        } catch (Throwable e) {
            status = AsyncTaskStatus.FAILED;
            log.error("asyncTaskMonitor: async task [{}] is failed, Error info:[{}]",
                    task.getId(),e.getMessage());
            e.printStackTrace();
        }
        task.setEndTime(new Date());
        task.setAsyncTaskStatus(status);
        taskManager.setTask(task);
        return value;
    }
}
